<template>
  <div>
    <el-main>
      <el-row>
        <el-col :span="12" :xs="24">
          <div style="font-size: 24px;font-weight:bold;margin-bottom: 20px;">添加走访</div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="12" :xs="24">
                <el-form-item label="企业名称">
                  <el-row style="">
                    <el-col :span="24">

                      <el-autocomplete clearable style="width: 100%;" class="inline-input" v-model="company"
                        :fetch-suggestions="querySearch" placeholder="请输入公司名称" :trigger-on-focus="false"
                        @change="handleSelect" @select="handleSelect">
                        <template slot-scope="{ item }">
                          <div class="name">{{ item.company }}</div>
                        </template>
                      </el-autocomplete>

                      <!--  <el-select style="width: 100%;" default-first-option allow-create v-model="company"
                        @change="SelectCompany" clearable filterable remote :remote-method="seachCompany"
                        placeholder="请输入公司名称">
                        <el-option v-for="item in seachCompanyList" :key="item.id" :label="item.company"
                          :value="item.id">
                        </el-option>
                      </el-select> -->
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item label="走访人员">
                  <el-select style="width: 100%;" filterable v-model="form.Visitpeople" multiple placeholder="">
                    <el-option v-for="item in Visitpeoplelist" :key="item.id" :label="item.username" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" :xs="24">
                <el-form-item class="Visitdate" label="走访时间">
                  <el-date-picker type="datetime" placeholder="" align="right" v-model="form.time"
                    value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="企业标签" v-if="labelList.length > 0">
              <div v-if="defaultLabel.length > 0">

                <el-tag @close="addLabel(item)" v-for="item in defaultLabel" :key="item.id" class="b_bule">{{
                  item.name
                }}</el-tag>
              </div>
              <div v-if="form.enterprise.length > 0">

                <el-tag closable @close="addLabel(item)" v-for="item in form.enterprise" :key="item.id" class="b_bule">
                  {{
                    item.name
                  }}</el-tag>
              </div>
              <el-button class="button_from_i" type="primary" round @click="addEnterprise">{{
                choose? '保存标签 -':
                  '添加标签+'
              }}
              </el-button>
              <div v-if="choose">
                <div>请选择下列标签：</div>
                <span v-for="item in labelList" :key="item.id" :class="{ b_bule: form.enterprise.indexOf(item) > -1 }"
                  class="addLabel b_choose" @click="addLabel(item)">{{ item.name }}</span>
              </div>
            </el-form-item>
          </el-form>
          <span class="dialog-footer">
            <el-button type="primary" @click="preservation">添加</el-button>
          </span>
        </el-col>
      </el-row>

    </el-main>
  </div>
</template>

<script>
import { seachCompany, labelTrue, staff, companyLabel, createVisit, pushUser, sendInfo, openidLogin } from '@/api/newuser'
import store from '@/store'
import { setToken } from '@/utils/auth'

export default {
  data() {
    return {
      id: JSON.parse(localStorage.getItem('data')).id,
      options: [],
      choose: false,
      Visit: false,
      SeachType: false,
      Visitpeoplelist: [],
      form: {
        company_id: Number,
        time: '',
        Visitpeople: [],
        enterprise: []
      },
      defaultLabel: [],
      company: '',
      seachCompanyList: [],
      labelList: [],
      SelectCompanyName: '',
    };
  },
  watch: {
    addVisit() {
      this.Visit = this.addVisit
      // console.log(this.addVisit)
    },
    add_form: {
      handler(newVal, oldVal) {
        this.form = newVal
      },
      immediate: true,
      deep: true,
    }
  },
  props: {
    addVisit: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    add_form: {
      type: Object,
      default: () => {
        return {
          name: '',
          time: '',
          Visitpeople: '',
          enterprise: []
        };
      }
    },
  },
  components: {},
  mounted() {
    // if (!(localStorage.getItem('userId') && localStorage.getItem('data'))) {
    //   this.$router.push({ path: '/web/small/login' })
    // }
    let openid = localStorage.getItem('openid')
    if (openid) {
      openidLogin({ openid: openid }).then(async res => {
        if (res.id) {
          //将res存入localStorage
          localStorage.setItem('data', JSON.stringify(res))
          // console.log(JSON.parse(localStorage.getItem('data')))
          localStorage.setItem('userId', res.id)
          // console.log(res, 'resbinding');
          let demo = await store.commit('user/SET_TOKEN', res.token)
          localStorage.setItem('token', res.token)
          setToken(res.token)

          this.staff()
          if (this.$route.query.company_name && this.$route.query.company_id) {
            this.form.company_id = this.$route.query.company_id
            this.company = this.$route.query.company_name
            labelTrue({ id: this.form.company_id })
            companyLabel({ id: this.form.company_id }).then(res => {
              this.defaultLabel = res.result
              this.labelList = res.list
            })
          }
        } else {
          this.$router.push({ path: '/web/small/login' })
        }
      })
    } else {
      this.$router.push({ path: '/web/small/login' })
    }
  },
  methods: {

    querySearch(queryString, cb) {
      seachCompany({ keword: queryString }).then(res => {
        this.seachCompanyList = res.slice(0, 1000)
        var restaurants = this.seachCompanyList;
        // console.log(restaurants);
        // var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(restaurants);
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleChange(item) {
      // console.log(item, 'item 5555');
      // this.company = item.company ? item.company : item
      // this.form = {
      //   company_id: Number,
      //   time: '',
      //   Visitpeople: [],
      //   enterprise: []
      // }
      // this.form.company_id = item.id ? item.id : item
      // labelTrue({ id: item.id ? item.id : item.company })
      // companyLabel({ id: item.id ? item.id : item.company }).then(res => {
      //   // console.log(res);
      //   this.defaultLabel = res.result
      //   this.labelList = res.list
      //   this.labelList.map(res_ => {
      //     res.label.map(res_1 => {
      //       if (res_.id == res_1.id) {
      //         this.form.enterprise.push(res_)
      //       }
      //     })
      //   })
      // })
    },
    handleSelect(item) {
      // console.log(item, 'item 111', item.id);
      if (this.SelectCompanyName != item) {
        this.company = item.company ? item.company : item
        this.form = {
          company_id: Number,
          time: '',
          Visitpeople: [],
          enterprise: []
        }
        this.SelectCompanyName = item.company ? item.company : item
        this.form.company_id = item.id ? item.id : item
        labelTrue({ id: item.id ? item.id : item })
        companyLabel({ id: item.id ? item.id : item }).then(res => {
          // console.log(res);
          this.defaultLabel = res.result
          this.labelList = res.list
          this.labelList.map(res_ => {
            res.label.map(res_1 => {
              if (res_.id == res_1.id) {
                this.form.enterprise.push(res_)
              }
            })
          })
        })
      }
    },
    staff() {
      staff({
        id: this.id,
        type: 1,
      }).then(res => {
        this.Visitpeoplelist = res
      })
    },
    SelectCompany(item) {
      // console.log(item);
      this.form = {
        company_id: Number,
        time: '',
        Visitpeople: [],
        enterprise: []
      }
      this.form.company_id = item
      this.choose = false
      if (item) {
        labelTrue({ id: item })
        companyLabel({ id: item }).then(res => {
          // console.log(res);
          this.defaultLabel = res.result
          this.labelList = res.list
          this.labelList.map(res_ => {
            res.label.map(res_1 => {
              if (res_.id == res_1.id) {
                this.form.enterprise.push(res_)
              }
            })
          })
        })
      } else {
        this.defaultLabel = []
        this.labelList = []
      }
    },
    seachInputType() {
      this.SeachType = false
    },
    //模糊查询
    seachCompany(query) {
      seachCompany({ keword: query }).then(res => {
        this.seachCompanyList = res.slice(0, 1000)
      })
    },
    //关闭弹窗
    close() {
      this.$emit('close');
    },
    //保存
    preservation() {
      // console.log(this.form.enterprise, this.form, 'this.form');
      let demolabel
      if (this.form.enterprise.length > 0) {
        demolabel = this.form.enterprise.map(item => {
          return item.id
        }).join(',')
      }
      createVisit(
        {
          user_id: this.id,
          company_id: this.form.company_id,
          date: this.form.time,
          visit: this.form.Visitpeople.join(','),
          label: demolabel
        }
      ).then(res => {
        //公众号推送
        pushUser({
          user_id: this.form.Visitpeople.join(','),
          type: 1,
          time: this.form.time,
          company_id: this.company
        }).then(res_ => {
          this.$message.success('走访人员推送成功')
        })

        //短信推送
        sendInfo({
          user_id: this.form.Visitpeople.join(','),
          type: 1,
          company: this.company,
          time: this.form.time
        }).then(res_ => {
          this.$message.success('短信推送成功')
        })

        this.$message.success('添加成功')
        //返回上一级路由
        this.$router.go(-1)
        // this.$router.push(
        //   {
        //     path: '/workWaitvisit',
        //     query: {
        //       type: 1
        //     }
        //   }
        // )
      }).catch(err => {
        this.$message.error(err.message)
      })
    },

    addEnterprise() {
      this.choose = !this.choose
    },
    addLabel(item) {
      let index = this.form.enterprise.indexOf(item)
      if (index == -1) {
        this.form.enterprise.push(item)
      } else {
        this.form.enterprise.splice(index, 1)
      }
    }
  },
};
</script>

<style scoped lang="less">
.el-main {
  margin: 20px 15px;
}

.seachCompanyList {
  position: absolute;
  top: 40px;
  background-color: #fff;
  z-index: 2;
  height: 200px;
  overflow: scroll;
  overflow-x: auto;
  border: 1px solid #f4f5f7;

  div {
    padding: 0 5px;
    cursor: pointer;
  }

  div:hover {
    background-color: #c1c1c1;
  }
}

.button_from_i {
  min-width: 125px;
  height: 38px;
  line-height: 0px;
  font-size: 14px;
  color: #3377FF;
  background-color: #ebf2ff;
  border: 1px solid #387DFF;
}

.dialog-footer {
  button {
    padding: 5px 30px;
    width: 139px;
    height: 38px;
    background: #387DFF;
    border: 1px solid #E8ECEF;
    border-radius: 19px;
    font-size: 14px;
  }
}

.b_bule {
  /*display: inline-block;*/
  background-color: #D3E2FF !important;
  margin: 3px 5px;
  border-radius: 5px;
  padding: 0px 10px;
  color: #387DFF;
  font-size: 12px;
  height: 20px;
  line-height: 20px;
  border: none !important;
}

.b_choose {
  display: inline-block;
  background-color: #ffffff;
  margin: 3px 5px;
  border-radius: 5px;
  padding: 0px 10px;
  color: #387DFF;
  font-size: 12px;
  height: 22px;
  line-height: 20px;
  border: 1px solid #387DFF;
  cursor: pointer;
}

::v-deep .el-table__row td:nth-child(6) .el-button {
  color: #23B899;
  background-color: #ecfaf7;
  border: none;
  font-size: 14px;
}

::v-deep input {
  border-radius: 38px;
  height: 38px;
  line-height: 38px;
}

::v-deep .el-input__icon {
  line-height: 38px;
  font-size: 16px;
}



.Visitdate {
  margin-top: 62px;
}

::v-deep .el-table__row td:nth-child(7) .el-button {
  color: #23B899;
  background-color: #ecfaf7;
  border: none;
}


::v-deep .el-dialog {
  border-radius: 10px;
}

::v-deep .el-dialog__header {
  .el-dialog__title {
    font-size: 22px;
    font-weight: bolder;
  }

  .el-dialog__headerbtn {
    i {
      position: absolute;
      border: 3px solid #fff;
      top: -50px;
      left: 30px;
      color: #fff;
      border-radius: 30px;
      font-size: 24px;
      font-weight: bolder;
    }
  }
}

::v-deep .el-form-item {
  .el-form-item__label {
    font-size: 14px;
    font-weight: initial;
  }

  .el-form-item__content {
    .el-input__inner {
      border-radius: 5px;
    }
  }
}

@media (max-width: 768px) {
  .el-main {
    margin: 0;
    height: 100vh;
  }

  .Visitdate {
    margin-top: 0;
  }

  .el-form-item__content {

    .el-select {
      width: 100%;
    }
  }

  ::v-deep .el-popper {
    left: 22px !important;
  }
}

@media (max-width: 1280px) {}

@media (max-width: 1360px) {}
</style>
